<?php

    class User extends FrontEnd_Controller {

        function User() {
            parent::FrontEnd_Controller();
            $this->load->model('User_m');
            $this->load->model('Seatting_admin_m');
            $this->load->helper('date');
            $this->load->library('email');
        }

        function login() {
            $utc = time();
            //validate login form//
            if ($this->input->post('submit')) {
                $formVal = array(
                array(
                'field' => 'email_login',
                'Label' => 'Email',
                'rules' => 'required|valid_email'
                ),
                array(
                'field' => 'pass_login',
                'Label' => 'Password',
                'rules' => 'required'
                )
                );
                $this->form_validation->set_rules($formVal);
                //------------------//
                if ($this->form_validation->run() == TRUE) {
                    $email = $this->input->post('email_login');
                    $password = md5($this->input->post('pass_login'));
                    $query1 = $this->User_m->get_deactivate_user($email);
                    if ($query1->num_rows > 0) {
                        $this->_data['login_error'] = "Account is banned!!!";
                        $this->display_view('home/index');
                    } else {
                        $query = $this->User_m->get_user($email, $password);
                        if ($query->num_rows > 0) {
                            $login_user = $query->row();
                            $data = array('last_login' => $utc);
                            $this->User_m->change_login_time($data, $login_user->id);
                            $this->session->set_userdata('display_name', $login_user->display_name);
                            $this->session->set_userdata('group_id', $login_user->group_id);
                            $this->session->set_userdata('user_id', $login_user->id);
                            $this->session->set_userdata('gravatar', $login_user->gravatar);
                            $nav_link = $this->session->userdata('smart_navigate_url') ? $this->session->userdata('smart_navigate_url') : base_url();
                            redirect($nav_link);
                        } else {
                            $this->_data['login_error'] = "Wrong email or password, Please try again";
                            $this->display_view('home/index');
                        }
                    }
                } else {
                    $this->_data['validate_error'] = TRUE;
                    $this->display_view('home/index');
                }
            } else {
                $this->display_view('home/index');
            }
        }

        function logout() {
            $this->session->unset_userdata('user_id');
            $nav_link = $this->session->userdata('smart_navigate_url') ? $this->session->userdata('smart_navigate_url') : base_url();
            redirect($nav_link);
            //redirect($this->_data['smart_navigate_url']);
        }

        function login_gardient() {
            if ($this->input->post('submit1')) {
                $formVal = array(array(
                'field' => 'gardient_name_login',
                'Label' => 'Gardient name',
                'rules' => 'required'
                ),
                array(
                'field' => 'password_login',
                'Label' => 'Password',
                'rules' => 'required'
                )
                );
                $this->form_validation->set_rules($formVal);
                if ($this->form_validation->run() === TRUE) {
                    $gardient_name = $this->input->post('gardient_name_login');
                    $password = md5($this->input->post('password_login'));
                    $query = $this->User_m->get_gardient($gardient_name, $password);
                    if ($query->num_rows > 0) {
                        $login_gardient = $query->row();
                        $this->session->set_userdata('gardient_name', $login_gardient->gardient_name);
                        $this->session->set_userdata('gardient_id', $login_gardient->id);
                        $this->session->set_userdata('avatar', $login_gardient->avatar);
                        $nav_link = $this->session->userdata('smart_navigate_url') ? $this->session->userdata('smart_navigate_url') : base_url();
                        redirect($nav_link);
                    } else {
                        $this->_data['login_gardient_error'] = "Wrong email or password, Please try again";
                        $this->display_view('home/index');
                    }
                } else {
                    $this->_data['validate_error_gardient'] = TRUE;
                    $this->display_view('home/index');
                }
            } else {
                $this->display_view('home/index');
            }
        }

        function logout_gardient() {
            $this->session->unset_userdata('gardient_id');
            $nav_link = $this->session->userdata('smart_navigate_url') ? $this->session->userdata('smart_navigate_url') : base_url();
            redirect($nav_link);
        }

        function register_gardient() {
            /* Captcha */
            $expiration_period = time() - 1800;
            $this->db->query("DELETE FROM captcha WHERE captcha_time < " . $expiration_period);
            $this->load->plugin('captcha');
            $vals = array(
            'word' => strtoupper(random_string('alnum', 6)),
            'img_path' => './assets/captcha/',
            'img_url' => base_url() . 'assets/captcha/',
            'font_path' => base_url() . 'system/fonts/texb.ttf',
            'img_width' => '150',
            'img_height' => 32,
            'expiration' => 300
            );

            $cap = create_captcha($vals);

            $cap_save = array(
            'captcha_id' => '',
            'captcha_time' => $cap['time'],
            'ip_address' => $this->input->ip_address(),
            'word' => $cap['word']
            );
            $query = $this->db->insert_string('captcha', $cap_save);
            $this->db->query($query);
            $this->_data['captcha_img'] = $cap['image'];
            /* End of captcha */
            $config['charset'] = 'utf-8';
            $config['wordwrap'] = TRUE;
            $config['mailtype'] = 'html';
            if ($this->input->post('submit')) {
                $formVal = array(
                array(
                'field' => 'gardient_name',
                'Label' => 'Gardient name',
                'rules' => 'required|callback_is_name_existe|xss_clean|max_length[20]'
                ),
                array(
                'field' => 'email',
                'Label' => 'Email',
                'rules' => 'trim|required|valid_email|callback_check_exist_email|xss_clean'
                ),
                array(
                'field' => 'password',
                'Label' => 'Password',
                'rules' => 'required|matches[confirm_pass]|min_length[5]'
                ),
                array(
                'field' => 'confirm_pass',
                'Label' => 'Confirm Password',
                'rules' => 'required'
                ),
                array(
                'field' => 'first_name',
                'Label' => 'First name',
                'rules' => 'required'
                ),
                array(
                'field' => 'last_name',
                'Label' => 'Last name',
                'rules' => 'required'
                ),
                array(
                'field' => 'phone',
                'Label' => 'Phone number',
                'rules' => 'required|min_length[10]'
                ),
                array(
                'field' => 'experience',
                'Label' => 'Experience number',
                'rules' => 'integer|required'
                ),
                array(
                'field' => 'address',
                'Label' => 'Address',
                'rules' => 'required'
                ),
                array(
                'field' => 'captcha',
                'Label' => 'Picture letters',
                'rules' => 'required|max_length[6]|callback_is_correct_captcha'
                )
                );
                $this->form_validation->set_rules($formVal);

                if ($this->form_validation->run() == TRUE) {
                    $image_path = './assets/avatar_gardient';
                    $thumb_path = $image_path . '/thumbs';
                    $config = array(
                    'allowed_types' => "jpg|jpeg|gif|png",
                    'upload_path' => $image_path,
                    'max_size' => 10000,
                    'encrypt_name' => TRUE
                    );
                    $this->_data['page_title'] = "Uploading...";
                    $this->load->library('upload', $config);

                    if ($this->upload->do_upload()) {
                        $upload_info = $this->upload->data();
                        $config = array(
                        'source_image' => $upload_info['full_path'], //get original image
                        'new_image' => $thumb_path, //save as new image //need to create thumbs first
                        'maintain_ratio' => true,
                        'width' => 300,
                        'height' => 200
                        );
                        $this->load->library('image_lib', $config); //load library
                        $this->image_lib->resize(); //do whatever specified in config
                        delete_pro_file($upload_info['full_path']);

                        $birthday = $this->input->post('birth_year') . '-' . $this->input->post('birth_month') . '-' . $this->input->post('birth_date') . ' ' . '06:00';
                        $dob_long = human_to_unix($birthday);
                        $email = $this->input->post('email');
                        $password = $this->input->post('password');
                        $confirm_password = $this->input->post('confirm_pass');
                        $data_account = array(
                        'password' => md5($password),
                        'email' => $this->input->post('email'),
                        'gardient_name' => $this->input->post('gardient_name')
                        );
                        $this->Seatting_admin_m->add_gardient($data_account);

                        $query_id_max = $this->Seatting_admin_m->get_account_id_max();
                        $user = $query_id_max->row();
                        $user_id = $user->new_id;
                        $display_name = $this->input->post('display_name');

                        $data_profile = array('gardient_id' => $user_id,
                        'first_name' => $this->input->post('first_name'),
                        'last_name' => $this->input->post('last_name'),
                        'dob' => $dob_long,
                        'gender' => $this->input->post('gender'),
                        'phone' => $this->input->post('phone'),
                        'experience' => $this->input->post('experience'),
                        'address' => $this->input->post('address'),
                        'avatar' => $upload_info['file_name'],
                        'available' => 1,
                        'post_code' => $this->input->post('post_code'),
                        'city' => $this->input->post('city')
                        );
                        $this->Seatting_admin_m->add_gardient_profile($data_profile);
                        $query = $this->User_m->get_gardient($this->input->post('gardient_name'), md5($password));
                        if ($query->num_rows > 0) {
                            $login_gardient = $query->row();
                            $this->session->set_userdata('gardient_name', $login_gardient->gardient_name);
                            $this->session->set_userdata('gardient_id', $login_gardient->id);
                            $this->session->set_userdata('avatar', $login_gardient->avatar);
                        }
                        //send mail
                        $From = 'administrator@lehu.com';
                        $this->email->from($From, 'Seatting-falin');
                        $this->email->to($this->input->post('email'));
                        $this->email->subject("s'inscrire dans Seatting-falin");
                        $message = 'Hello ' .$login_gardient->gardient_name . 'Merci de vous enregistrer avec Seatting-falin. Bienvenue!';
                        $this->email->message($message);
                        $this->email->send();
                        //end send
                        $this->display_view('home/index');
                    } else {
                        $birthday = $this->input->post('birth_year') . '-' . $this->input->post('birth_month') . '-' . $this->input->post('birth_date') . ' ' . '06:00';
                        $dob_long = human_to_unix($birthday);
                        $email = $this->input->post('email');
                        $password = $this->input->post('password');
                        $confirm_password = $this->input->post('confirm_pass');
                        $data_account = array(
                        'password' => md5($password),
                        'email' => $this->input->post('email'),
                        'gardient_name' => $this->input->post('gardient_name')
                        );
                        $this->Seatting_admin_m->add_gardient($data_account);

                        $query_id_max = $this->Seatting_admin_m->get_account_id_max();
                        $user = $query_id_max->row();
                        $user_id = $user->new_id;
                        $display_name = $this->input->post('display_name');

                        $data_profile = array('gardient_id' => $user_id,
                        'first_name' => $this->input->post('first_name'),
                        'last_name' => $this->input->post('last_name'),
                        'dob' => $dob_long,
                        'gender' => $this->input->post('gender'),
                        'phone' => $this->input->post('phone'),
                        'experience' => $this->input->post('experience'),
                        'address' => $this->input->post('address'),
                        'available' => 1,
                        'post_code' => $this->input->post('post_code'),
                        'city' => $this->input->post('city')
                        );
                        $this->Seatting_admin_m->add_gardient_profile($data_profile);
                        $query = $this->User_m->get_gardient($this->input->post('gardient_name'), md5($password));
                        if ($query->num_rows > 0) {
                            $login_gardient = $query->row();
                            $this->session->set_userdata('gardient_name', $login_gardient->gardient_name);
                            $this->session->set_userdata('gardient_id', $login_gardient->id);
                            $this->session->set_userdata('avatar', $login_gardient->avatar);
                        }
                        $From = 'administrator@lehu.com';
                        $this->email->from($From, 'Seatting-falin');
                        $this->email->to($this->input->post('email'));
                        $this->email->subject("s'inscrire dans Seatting-falin");
                         $message = 'Hello ' .$login_gardient->gardient_name . '.Merci de vous enregistrer avec Seatting-falin. Bienvenue!';
                        $this->email->message($message);
                        $this->email->send();
                        //end send
                        $this->display_view('home/index');
                    }
                } else {
                    $this->display_view('home/register_gardient');
                }
            } else {
                $this->display_view('home/register_gardient');
            }
        }

        function is_correct_captcha($captcha) {
            $expiration = time() - 1800;
            $sql = "SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND captcha_time > ?";
            $binds = array($captcha, $this->input->ip_address(), $expiration);
            $query = $this->db->query($sql, $binds);
            $row = $query->row();

            if ($row->count == 0) {
                $this->form_validation->set_message('is_correct_captcha', 'Please enter correct word in the picture!');
                return FALSE;
            }
            return TRUE;
        }

        function forgot_pass_gardient() {
            $config = array(
            array(
            'field' => 'email',
            'label' => 'Your email',
            'rules' => 'required|valid_email'
            )
            );
            $this->form_validation->set_rules($config);
            if ($this->input->post('submit')) {
                if ($this->form_validation->run()) {
                    $temp_pass = random_string('alnum', 16);
                    $email = $this->input->post('email');
                    $this->load->library('email');
                    $account_info = $this->User_m->get_account_infor_by_email($email);
                    if ($account_info->num_rows() > 0) {
                        $account = $account_info->row();
                        $data = array(
                        'password' => md5($temp_pass)
                        );
                        if ($this->User_m->update_temp_pass($email, $data) > 0) {
                            $this->email->from('administrator@lehu.com', 'Seatting-falin');
                            $this->email->to($email);
                            $this->email->subject('Mot de passe de recupiration');
                            $message = 'Hello ' . $account->gardient_name . '. Please use following account and temporary pass to login at lehu: User: ' . $account->gardient_name . ' and Temporary pass: ' . $temp_pass;
                            $this->email->message($message);
                            if ($this->email->send()) {
                                $this->display_view('gardient/recover_success');
                            } else {
                                $this->_data['error'] = "Impossible d'envoyer du courrier";
                                $this->display_view('gardient/forgot_pass');
                            }
                        }
                    } else {
                        $this->_data['error'] = "votre e-mail n'a pas été enregistré";
                        $this->display_view('gardient/forgot_pass');
                    }
                } else {
                    $this->display_view('gardient/forgot_pass');
                }
            } else {
                $this->display_view('gardient/forgot_pass');
            }
        }

        function is_name_existe() {
            $name = $this->input->post('gardient_name');
            $query = $this->Seatting_admin_m->is_name_existe($name);
            if ($query->num_rows() > 0) {
                $this->form_validation->set_message('is_name_existe', 'The name was exist');
                return FALSE;
            } else {
                return TRUE;
            }
        }

        function check_exist_email() {
            $email = $this->input->post('email');
            $query = $this->User_m->check_email($email);
            if ($query->num_rows() > 0) {
                $this->form_validation->set_message('check_exist_email', 'The email was exist');
                return FALSE;
            } else {
                return TRUE;
            }
        }

        function edit_profile($id=0) {
            $birthday = $this->input->post('birth_year') . '-' . $this->input->post('birth_month') . '-' . $this->input->post('birth_date') . ' ' . '06:00';
            $dob_long = human_to_unix($birthday);
            $gardient = $this->Seatting_admin_m->get_detail_gardient($id);
            $this->_data['gardient_data'] = $gardient;

            $this->_data['erreur'] = "";
            $config = array(
            array(
            'field' => 'first_name',
            'label' => 'First name',
            'rules' => 'required'
            ),
            array(
            'field' => 'last_name',
            'label' => 'Last name',
            'rules' => 'required'
            ),
            array(
            'field' => 'address',
            'label' => 'address',
            'rules' => 'required'
            ),
            array(
            'field' => 'phone',
            'Label' => 'Phone number',
            'rules' => 'min_length[10]'
            )
            );
            $this->form_validation->set_rules($config);
            if ($this->input->post('submit')) {
                $image_path = './assets/avatar_gardient';
                $thumb_path = $image_path . '/thumbs';
                $config = array(
                'allowed_types' => "jpg|jpeg|gif|png",
                'upload_path' => $image_path,
                'max_size' => 10000,
                'encrypt_name' => TRUE
                );
                $this->_data['page_title'] = "Uploading...";
                $this->load->library('upload', $config);

                if ($this->upload->do_upload()) {
                    $upload_info = $this->upload->data();
                    $config = array(
                    'source_image' => $upload_info['full_path'], //get original image
                    'new_image' => $thumb_path, //save as new image //need to create thumbs first
                    'maintain_ratio' => true,
                    'width' => 300,
                    'height' => 200
                    );
                    $this->load->library('image_lib', $config); //load library
                    $this->image_lib->resize(); //do whatever specified in config
                    delete_pro_file($upload_info['full_path']);

                    if ($this->form_validation->run()) {
                        $data = array(
                        'first_name' => $this->input->post('first_name'),
                        'last_name' => $this->input->post('last_name'),
                        'gender' => $this->input->post('gender'),
                        'dob' => $dob_long,
                        'phone' => $this->input->post('phone'),
                        'experience' => $this->input->post('experience'),
                        'address' => $this->input->post('address'),
                        'avatar' => $upload_info['file_name']
                        );
                        $this->User_m->edit_profile($data, $id);
                        $nav_link = $this->session->userdata('smart_navigate_url') ? $this->session->userdata('smart_navigate_url') : base_url();
                        redirect($nav_link);
                    } else {
                        $this->display_view('home/edit_profile');
                    }
                } else {
                    if ($this->form_validation->run()) {
                        $data = array(
                        'first_name' => $this->input->post('first_name'),
                        'last_name' => $this->input->post('last_name'),
                        'gender' => $this->input->post('gender'),
                        'dob' => $dob_long,
                        'phone' => $this->input->post('phone'),
                        'experience' => $this->input->post('experience'),
                        'address' => $this->input->post('address')
                        );
                        $this->User_m->edit_profile($data, $id);
                        $nav_link = $this->session->userdata('smart_navigate_url') ? $this->session->userdata('smart_navigate_url') : base_url();
                        redirect($nav_link);
                    } else {
                        $this->display_view('home/edit_profile');
                    }
                }
            } else {
                $this->display_view('home/edit_profile');
            }
        }

        function change_pass($id) {
            $this->_data['erreur'] = "";

            $config = array(
            array(
            'field' => 'apass',
            'label' => 'Ancien mot de passe',
            'rules' => 'required|md5'
            ),
            array(
            'field' => 'npass',
            'label' => 'Nouveau mot de passe',
            'rules' => 'required|matches[confirm_npass]|md5'
            ),
            array(
            'field' => 'confirm_npass',
            'label' => 'Confirmation du mot de passe',
            'rules' => 'required|md5'
            )
            );
            $this->form_validation->set_rules($config);
            if ($this->form_validation->run()) {
                $pass = $this->input->post('apass');
                $query = $this->User_m->is_password($pass, $id);
                if ($query) {
                    $data = array('password' => $this->input->post('npass'));
                    $query = $this->User_m->change_pass($data, $id);
                    $nav_link = $this->session->userdata('smart_navigate_url') ? $this->session->userdata('smart_navigate_url') : base_url();
                    redirect($nav_link);
                } else {
                    $this->_data['erreur'] = "Mot de passe incorrect";
                    $this->display_view('home/change_pass');
                }
            }else
                $this->display_view('home/change_pass');
        }

        function set_unavailable_gardient($id) {
            is_admin();
            $this->Seatting_admin_m->set_unavailable_gardient($id);
            redirect('user/edit_profile' . '/' . $id);
        }

        function set_available_gardient($id) {
            is_admin();
            $this->Seatting_admin_m->set_available_gardient($id);
            redirect('user/edit_profile' . '/' . $id);
        }

    }

?>
